import os
import time
import base64
import urllib
import json
import requests
import datetime
from  requests.packages import urllib3
import configparser
import os
import sys
import ssl
class Config(configparser.RawConfigParser):
    def __init__(self,fileName=None,postfix="ini"):
        if(fileName==None):
            fileName = os.path.basename(sys.argv[0])
            fileName=fileName.split(".")[0]

        self.__fileName="{}.{}".format(fileName,postfix)
        if(not os.path.exists(self.__fileName)):
            open(self.__fileName,"a").close()
        super().__init__()
        self.read(self.__fileName,"utf-8")
    def set(self,section, option, value=None):
        if(not self.has_section(section)):
            self.add_section(section)
        super().set(section, option, value)

    def getMYSQL(self):
        mysqlConfig=dict(self.items("MYSQL"))
        mysqlConfig["log"]=Log()
        return mysqlConfig
        
    def defaultMYSQL(self):
        self.setArray("MYSQL",[
            {"host":"192.168.18.25"},
            {"port":"3306"},
            {"user":"root"},
            {"password":"Aa159357"},
            {"database":"base"},
        ])
        self.save()

    def setArray(self,section, arr):
        if(not self.has_section(section)):
            self.add_section(section)
        for item in arr:
            super().set(section,tuple(item.keys())[0], tuple(item.values())[0])

    def save(self):
        with open(self.__fileName, 'w') as configfile:
            self.write(configfile)

class Log:
    def __init__(self,fileName=None):
        if(fileName==None):
            fileName = os.path.basename(sys.argv[0])
            fileName=fileName.split(".")[0]
        self.__fileName=fileName
        self.__state=True

    def Close(self):
        self.__state=False

    def Open(self):
        self.__state=True

    def log(self,data,logType="普通日志"):
        if(not self.__state):
            return
        t=time.localtime()
        filename="{}".format(self.__fileName)
        path="log/{}".format(time.strftime("%Y%m%d",t))
        self.__create_document(path)
        with open("{}/{}.log".format(path,filename),"a",encoding="utf-8") as f:
            f.write("[{}] {}------{}\r\n".format(logType,data,time.strftime("%Y-%m-%d %H:%M:%S",t)))
    def __create_document(self,path):
        try:
            if not os.path.exists(path):
                os.makedirs(path)
        except:
            pass
    def error(self,data,logType="普通错误"):
        if(not self.__state):
            return
        t=time.localtime()
        filename="{}_{}".format(self.__fileName,"error")
        path="log/{}".format(time.strftime("%Y%m%d",t))
        self.__create_document(path)
        with open("{}/{}.log".format(path,filename),"a",encoding="utf-8") as f:
            f.write("[{}] {}------{}\r\n".format(logType,data,time.strftime("%Y-%m-%d %H:%M:%S",t)))


import time

def decLog(fun):
    def wrapper(*args,**kwargs):
        n_log=Log()
        n_log.log("start:"+fun.__name__+str(args)+str(kwargs))
        result=None
        try:
            result=fun(*args,**kwargs)
        except Exception as e:
            n_log.error("error:"+fun.__name__+str(args)+str(kwargs)+str(e))
            # raise  e
        n_log.log("end:"+fun.__name__+str(args)+str(kwargs))
        return result
    return wrapper

#进度条展示
def progress(value,text="",chart="▉"):
    a = int((value)/4)
    b = int(25-a)
    sys.stdout.write('\r|%s%s|%d%% %s\r'%(a*'▇',b*'  ',value,text))
    sys.stdout.flush()

def now(format="%Y-%m-%d %H:%M:%S"):
    return time.strftime(format,time.localtime())

def datediff(max_time,min_time):
    d1=datetime.datetime.strptime(min_time, '%Y-%m-%d %H:%M:%S')
    d2=datetime.datetime.strptime(max_time, '%Y-%m-%d %H:%M:%S')
    if(d1>d2):
        return -(d1-d2).seconds
    else:
        return (d2-d1).seconds

def date_style_transfomation(date, format_string1="%Y-%m-%d %H:%M:%S",format_string2="%Y%m%d%H%M%S00"):
    time_array = time.strptime(date, format_string1)
    str_date = time.strftime(format_string2, time_array)
    return str_date


def scene_to_face(base64_image):
    url="http://127.0.0.1:22280/scene_to_face/200"
    data={
            "image":base64_image
        }
    headers={
            "content-type":"application/json",
            "accept":"application/json"
        }
    res=requests.post(url=url,data=json.dumps(data),headers=headers)
    if(res.status_code==200):
        try:
            data=json.loads(res.text)
        except Exception as e:
            data=None
        res.close()
        return data
    else:
        res.close()
        return None

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False

def postJson(url,data):
    try:
        headers={
                "content-type":"application/json",
                "accept":"application/json"
            }
        urllib3.disable_warnings()
        res=requests.post(url=url,data=json.dumps(data),headers=headers,verify=False)
        if(res.status_code==200):
            try:
                data=json.loads(res.text)
            except Exception as e:
                data=res.text
            res.close()
            return data
        else:
            res.close()
            return res.status_code
    except Exception as e:
         return e


def quality(base64_image):
    url="http://127.0.0.1:22280/quality"
    data={
            "image":base64_image
        }
    headers={
            "content-type":"application/json",
            "accept":"application/json"
        }
    res=requests.post(url=url,data=json.dumps(data),headers=headers)
    if(res.status_code==200):
        try:
            data=json.loads(res.text)
        except Exception as e:
            data=None
        res.close()
        return data
    else:
        res.close()
        return None

def webfile_to_base64(url):
    bydata=webfile_to_byte(url)
    base64_data=None
    if(bydata!=None):
        base64_data = base64.b64encode(bydata)
        base64_data = base64_data.decode()
    return base64_data

def webfile_to_byte(url):
    data=None
    try:
        ssl._create_default_https_context = ssl._create_unverified_context
        rsp=urllib.request.urlopen(url)
        data=rsp.read()
    except Exception as e:
        pass
    return data

def byte_to_file(bydata,path):
    with open(path,"wb") as f:
        f.write(bydata)

def base64_to_file(image,path):
    try:
        imagedata = base64.b64decode(image)
        file = open(path,"wb")
        file.write(imagedata)
        file.close()
    except Exception as e:
        print(e)
        return None
    return True

def base64_to_byte(image):
    return base64.b64decode(image)

def byte_to_base64(bydata):
    base64_data = base64.b64encode(bydata)
    return  base64_data.decode()

def file_to_base64(path):
    base64_data=None
    try:
        if os.path.exists(path):
            with open(path, 'rb') as f:
                base64_data = base64.b64encode(f.read())
                base64_data = base64_data.decode()
    except Exception as e:
        pass
    return base64_data

def file_to_byte(path):
    data=None
    try:
        if os.path.exists(path):
            with open(path, 'rb') as f:
                data = f.read()
    except Exception as e:
        pass
    return data
